package 实验四6;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MultiThreadVoting {
    static class Candidate {
        private final String name;
        private int votes;
        private final Lock lock = new ReentrantLock();

        public Candidate(String name) {
            this.name = name;
            this.votes = 0;
        }

        public void vote() {
            lock.lock();
            try {
                votes++;
            } finally {
                lock.unlock();
            }
        }

        public int getVotes() {
            return votes;
        }

        public String getName() {
            return name;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // 初始化候选人
        Candidate[] candidates = {
            new Candidate("张三"),
            new Candidate("李四"),
            new Candidate("王五")
        };

        int voterCount = 100;
        Thread[] voters = new Thread[voterCount];
        Random random = new Random();

        // 创建投票者线程
        for (int i = 0; i < voterCount; i++) {
            voters[i] = new Thread(() -> {
                int candidateIndex = random.nextInt(candidates.length);
                candidates[candidateIndex].vote();
            });
            voters[i].start();
        }

        // 等待所有投票者完成
        for (Thread voter : voters) {
            voter.join();
        }

        // 输出结果
        System.out.println("投票结果:");
        for (Candidate candidate : candidates) {
            System.out.println(candidate.getName() + ": " + candidate.getVotes() + " 票");
        }
    }
}
